package com.lanou.lenanapp.activity;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;


import com.lanou.lenanapp.R;
import com.lanou.lenanapp.db.DatabaseHelper;
import com.lanou.lenanapp.entity.greendao.LoginOneEntity;
import com.lanou.lenanapp.fragment.ImageFragment;
import com.lanou.lenanapp.fragment.JokeFragment;
import com.lanou.lenanapp.view.CircleImage;
import com.lanou.lenanapp.view.CustomDialog;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    private TabHost mhost;
    private FragmentManager fm;
    private Toolbar toolbar;
    private CircleImage imageView;//头像图片
    private ContentResolver cr;
    private TextView mainName;
    private DatabaseHelper helper;
    private NavigationView navigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(toolbar);

         final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        drawer.setDrawerListener(toggle);


        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        init();
        initFragment();

    }

    //主页tabhost
    private void init() {
        cr = getContentResolver();
        imageView = (CircleImage) navigationView.getHeaderView(0).findViewById(R.id.imageView);
        imageView.setOnClickListener(this);//主页头像
        mainName = (TextView) navigationView.getHeaderView(0).findViewById(R.id.mainName);
        helper = DatabaseHelper.getHelper();

        mhost = (TabHost) findViewById(android.R.id.tabhost);
        mhost.setup();

        TabHost.TabSpec joke = mhost.newTabSpec("joke");
        joke.setIndicator("段子");
        joke.setContent(R.id.jokeFragment);
        mhost.addTab(joke);

        TabHost.TabSpec image = mhost.newTabSpec("image");
        image.setIndicator("趣图");
        image.setContent(R.id.imageFragment);
        mhost.addTab(image);



        setHeaderIcon();
    }

    /**设置头像**/
    private void setHeaderIcon() {
        List<LoginOneEntity> list = helper.queryLoginOne();
        if (list != null && list.size() > 0) {
            String n = list.get(0).getOnephone();
            File file = new File(Environment.getExternalStorageDirectory() + "/" + n + ".jpg");
            if (file.exists()) {
                Bitmap bitmap2 = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + n + ".jpg");
                imageView.setImageBitmap(bitmap2);
            }
        }
    }

    /**
     * fragment替换占位
     * **/
    public void initFragment() {
        fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.jokeFragment, new JokeFragment());
        ft.replace(R.id.imageFragment, new ImageFragment());

        ft.commit();

        //主页抽屉头像旁边的昵称显示
        List<LoginOneEntity> list = helper.queryLoginOne();
        if (list != null && list.size() > 0){
            mainName.setText(list.get(0).getOnename());
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 抽屉按钮对应的页面
     * **/
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_joke :
                Intent intent = new Intent(this, MainActivity.class);
                toolbar.setTitle("首页");
                break;
            case R.id.nav_contribute:
                Intent intent1 = new Intent(this, ContributionActivity.class);
                startActivity(intent1);//网友投稿区
                this.finish();
                break;
            case R.id.nav_affiche:
                Intent intent2 = new Intent(this, AfficheActivity.class);
                startActivity(intent2);//公告牌
                break;
            case R.id.nav_collect:
                Intent intent3 = new Intent(this, CollectActivity.class);
                startActivity(intent3);//收藏
                break;
            case R.id.nav_set:
                Intent intent4 = new Intent(this, SetActivity.class);
                startActivity(intent4);//设置
                break;
            case R.id.nav_id:
                Intent intent5 = new Intent(this, AccountActivity.class);
                startActivity(intent5);//账号管理
                break;
            case R.id.nav_special:
                Intent intent6 = new Intent(this, SpecialActivity.class);
                startActivity(intent6);//专辑
                break;
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * 点击抽屉上方的圆图片修改头像
     * **/
    @Override
    public void onClick(View v) {
        List<LoginOneEntity> list = helper.queryLoginOne();
        if (list != null && list.size() > 0){
            isLogin();
        }else {
            noLogin();
        }
    }

    /**
     * 如果未登录弹出框
     * **/
    private void noLogin() {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setMessage("您还未登录,请先登录再设置头像");
        builder.setTitle("温馨提示");
        builder.setPositiveButton("登录", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }


    /**
     * 已经登录时的弹出框
     * **/
    private void isLogin() {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setMessage("您要更改头像么");
        builder.setTitle("温馨提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 200);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();

    }


    /**
     * 照片图库回调 并在sd卡新建文件 图片绑定账号
     * **/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0){
            return;
        }
        if (data != null && requestCode == 200 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            Cursor cursor = cr.query(uri, null, null, null, null);
            Bitmap bitmap;
            if (cursor != null) {
                while(cursor.moveToNext()){
                    //找到文件路径
                    String url = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    //取到bitmap
                    bitmap = BitmapFactory.decodeFile(url);
                    List<LoginOneEntity> list = helper.queryLoginOne();//查询单独数据库
                    if (list != null && list.size() > 0){
                        String phone = list.get(0).getOnephone();
                        //新建一个文件 给文件一个路径 en..是取sd卡得路径后缀是图片的路径
                        File file = new File(Environment.getExternalStorageDirectory() + "/" + phone + ".jpg");
                        try {
                            if (!file.exists()){
                                file.createNewFile();
                            }
                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                            Bitmap bitmap1 = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + phone + ".jpg");
                            imageView.setImageBitmap(bitmap1);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                cursor.close();
            }
        }

    }
}
